﻿using Edu.Common;
using Edu.Common.Logs;
using Edu.Common.NLogs;
using MainApp.Utils;
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;

namespace MainApp
{
    /// <summary>
    /// App.xaml 的交互逻辑
    /// </summary>
    public partial class App : Application
    {
        private static Mutex _appMutex;
        private ILogger _logger;
        App()
        {
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;
            DispatcherUnhandledException += App_DispatcherUnhandledException;
            CreateAppKey();
            //注册日志提供器
            NLogProvider.ChangeNLogOutPath(AppInfo.APP_LOG_PATH, $"{AppInfoBase.APP_ROOT}NLog.config");
            var logProvider = new NLogProvider();
            //注册日志提供器
            LogManager.RegisterProvider(logProvider);
            //清理日志
            logProvider.ClearLogsAsync();
        }
        /// <summary>
        /// 创建应用程序标识
        /// </summary>
        private static void CreateAppKey()
        {
            //检查程序的其他实例是否已经存在
            var appKey = "0FE46D3E-BECD-4956-BBB9-D613FB80BC17";
            var mutex = new Mutex(true, appKey, out bool ret);
            //创建程序实例
            if (!ret)
            {
                //再次检查是否已经存在实例
                MessageBox.Show("请勿重复启动此程序！", "提示信息");
                //退出程序
                Process.GetCurrentProcess().Kill();
                return;
            }
            _appMutex = mutex;
        }
        private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            OnException(e.ExceptionObject as Exception);
        }
        private void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            var handled = OnException(e.Exception);
            e.Handled = handled;
        }
        private void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
        {
            var handled = OnException(e.Exception);
            if (!handled) return;
            e.SetObserved();
        }
        private bool OnException(Exception exception)
        {
            _logger = _logger ?? LogManager.GetLogger<App>();
            _logger?.Error("", exception);
            return true;
        }
    }
}
